﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace Knowledgecast.Twitter.WPF
{
    public class TimeConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                DateTime date = (DateTime)value;
                return GetHumanTime(date);
            }
            else
            {
                return string.Empty;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion

        private string GetHumanTime(DateTime date)
        {
            string humanTimeString = string.Empty;
            if (date.Date == DateTime.Today)
            {
                TimeSpan span = DateTime.Now.Subtract(date);
                if (span.Hours == 1)
                {
                    humanTimeString = "About an hour ago";
                }
                else if (span.Hours == 0)
                {
                    if (span.Minutes < 5)
                    {
                        humanTimeString = "Moments ago";
                    }
                    else
                    {
                        humanTimeString = span.Minutes + " minutes ago";
                    }
                }
                else if (span.Hours > 0)
                {
                    humanTimeString = span.Hours + " hours ago";
                }
            }
            else
            {
                TimeSpan span = DateTime.Today.Subtract(date.Date);

                if (span.Days == 1)
                {
                    humanTimeString = "Yesterday";
                }
                else if (span.Days < 7)
                {
                    humanTimeString = "on " + date.DayOfWeek.ToString();
                }
                else if (span.Days > 7 && span.Days < 14)
                {
                    humanTimeString = "Last week";
                }
                else
                {
                    humanTimeString = "on " + date.ToShortDateString();
                }
            }

            return humanTimeString;
        }
    }
}
